package com.polaris.live.popup

import android.content.Context
import androidx.recyclerview.widget.GridLayoutManager
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BottomPopupView
import com.polaris.live.R
import com.polaris.live.adapter.backpack.BackPackDiscountAdapter
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.util.NavigationBarUtils
import com.polaris.live.common.util.ViewUtils
import com.polaris.live.databinding.PopupDiscountBinding
import com.polaris.live.resp.back_resp.UserBackpackConsumableResp

/**
 * DiscountPopup      折扣Pop
 *
 * @author Created by 天晴 on 2024/11/7/023 14:08
 */
class DiscountPopup(
    context: Context,
    private val title: String,
    private val data: List<UserBackpackConsumableResp>,
    private val needAddNull: Boolean,//首位是否添加不使用
    private val callback: (data: UserBackpackConsumableResp?) -> Unit,
) : BottomPopupView(context) {

    private lateinit var mBinding: PopupDiscountBinding

    private val mAdapter by lazy { BackPackDiscountAdapter() }
    override fun getImplLayoutId(): Int {
        return R.layout.popup_discount
    }

    override fun onCreate() {
        super.onCreate()
        mBinding = PopupDiscountBinding.bind(popupImplView)
        ViewUtils.setMargin(mBinding.bottomView, 0, 0, 0, NavigationBarUtils.getNavigationBarHeight(context))
        mBinding.recycler.apply {
            layoutManager = GridLayoutManager(context, 3)
            adapter = mAdapter
            itemAnimator = null
        }
        mAdapter.setList(data)
        if (needAddNull) {
            mAdapter.addData(0, "")
        }
        mAdapter.setOnItemClickListener { _, _, position ->
            val item = mAdapter.getItemOrNull(position)
            if (item is UserBackpackConsumableResp) {
                callback.invoke(item)
            } else {
                callback.invoke(null)
            }
            dismiss()
        }
        mBinding.apply {
            tvTitle.text = title
            btnClose.setOnSingleClickListener {
                dismiss()
            }
        }
    }

    companion object {

        const val DISCOUNT_CARD = 4  //折扣卡
        const val VOUCHER = 5  //代金券

        fun show(
            context: Context,
            title: String,
            list: List<UserBackpackConsumableResp>,
            needAddNull: Boolean = true,
            callback: (data: UserBackpackConsumableResp?) -> Unit,
        ) {
            XPopup.Builder(context)
                .isViewMode(false)
                .hasShadowBg(true)
                .moveUpToKeyboard(false)
                .isDestroyOnDismiss(true)
                .asCustom(DiscountPopup(context, title, list, needAddNull, callback))
                .show()
        }
    }
}